#include "ResBitmapText.h"
#include "D3D9Engine.h"

CResourceBitmapText::CResourceBitmapText()
{
	this->m_textChanged		= false;
	this->m_text			= 0;

	this->m_sourceTexture	= NULL;
	this->m_spriteInterface	= NULL;

	this->_type = NODE_ENTITY_ELEMENT;
	this->_entity = ENTITY_TEXT;

	this->SetColliding(false);
}

CResourceBitmapText::~CResourceBitmapText()
{
}

bool CResourceBitmapText::CreateBitmapText(const char *_text, CResourceBitmapFont *_fontType, DWORD _color)
{
	this->m_textChanged	= true;
	this->m_text		= (char*) _text;
	this->m_fontType	= _fontType;
	this->m_color		= _color;

	return true;
}

bool CResourceBitmapText::OnInitResource(ICompHandler *_handler)
{
	HRESULT hres;

	CD3D9Engine *ptr_engine = (CD3D9Engine*) _handler;

	if (ptr_engine != NULL)
	{
		hres = D3DXCreateSprite(ptr_engine->GetDevice(), &this->m_spriteInterface);

		if (FAILED(hres))
			return false;

		hres = D3DXCreateTexture(ptr_engine->GetDevice(), 
								 ptr_engine->GetWindowWidth(), 
								 ptr_engine->GetWindowHeight(), 
								 1, 
								 D3DUSAGE_RENDERTARGET, 
								 D3DFMT_A8R8G8B8, 
								 D3DPOOL_DEFAULT, 
								 &this->m_sourceTexture);

		if (FAILED(hres))
			return false;

		this->_renderedSize.top = 0;
		this->_renderedSize.bottom = ptr_engine->GetWindowHeight();
		this->_renderedSize.left = 0;
		this->_renderedSize.right = ptr_engine->GetWindowWidth();

		this->m_textChanged = true;

		return true;
	}

	return false;
}

bool CResourceBitmapText::OnFreeResource(ICompHandler *_handler)
{
	SAFE_RELEASE(this->m_sourceTexture);
	SAFE_RELEASE(this->m_spriteInterface);

	return true;
}

void CResourceBitmapText::Render(IDirect3DDevice9 *_device, D3DXMATRIX *_transformation)
{
	if (this->m_textChanged)
	{
		this->m_textChanged = false;
		this->m_fontType->RenderBitmapText(this->m_text, _device, &this->m_sourceTexture);
	}

	D3DXMATRIX transformation = (_transformation == NULL)? this->WorldTransformation : (*_transformation);

	this->m_spriteInterface->Begin(D3DXSPRITE_ALPHABLEND);

	this->m_spriteInterface->SetTransform(&transformation);

	this->m_spriteInterface->Draw(this->m_sourceTexture, &this->_renderedSize, NULL, NULL, this->m_color);

	this->m_spriteInterface->End();
}


void CResourceBitmapText::SetText(const char *_text)
{
	//if(strcmp(this->m_text, _text) != 0)
	{
		this->m_text = (char*) _text;
		this->m_textChanged = true;
	}

}